import axios from 'axios'
import { ElNotification } from 'element-plus'
export default {
  // 开启读卡器
  async takeOn(ip, port) {
    const url = `http://${ip}:${port}/takeon`
    try {
      const response = await axios.get(url, { timeout: 10000 })
      if (response.data.includes('ok')) {
        // setTimeout(() => takeOn(ip, port), 200); // 延迟200毫秒后再次请求数据
        ElNotification({
          type: 'success',
          message: 'RFID扫描已开启',
        })
      }
    } catch (error) {
      this.$message.warning('连接失败')
    }
  },
  // 关闭读卡器
  async takeOff(ip, port) {
    let count = 0
    const rfidIp = localStorage.getItem('rfidIp')
    if (!rfidIp) {
      this.$message.warning('连接失败')
      return
    }
    const url = `${rfidIp.replace(/"/g, '')}:${port}/takeoff`
    try {
      const response = await axios.get(url, { timeout: 1000 })
      if (response.data.includes('ok')) {
        if (count >= 2) {
          return
        }
        count++ // 增加计数器
        setTimeout(() => this.takeOff(ip, port), 200) // 延迟200毫秒后再次请求数据
        ElNotification({
          type: 'warning',
          message: 'RFID扫描已关闭',
        })
      }
    } catch (error) {
      this.$message.warning('连接失败')
    }
  },
  // 写卡  不需要开启读卡器
  async setRfid(e) {
    const rfidIp = localStorage.getItem('rfidIp')
    if (!rfidIp) {
      ElNotification({
        message: '连接失败,请登录馆员工作站',
        type: 'warning',
      })
      return
    }
    const url = `${rfidIp.replace(/"/g, '')}:80/setrfid/${e}`
    try {
      const response = await axios.get(url)
      return response.data
    } catch (error) {
      ElNotification({
        message: '请求失败，请检查网络连接',
        type: 'error',
      })
      throw error
    }
  },

  // 定时请求数据
  async getRifd(ip, port, type) {
    const url = `http://${ip}:${port}/getrfid?deviceType=${type}`
    try {
      const response = await axios.get(url, { timeout: 10000 })
      const result = eval(`(${response.data})`).result
      const uniqueIds = Array.from(new Set(result.map((item) => item.ID)))
      return uniqueIds
    } catch (error) {
      console.error('请求失败:', error)
      throw error
    }
  },

  async axiosIp(ip, params) {
    try {
      const response = await axios.post(`http://${ip}`, params)
      return response.data
    } catch (error) {
      console.error('请求失败:', error)
      throw error
    }
  },
}
